#!/usr/bin/python
#coding:utf-8

import oauth2 as oauth
from oauthtwitter import OAuthApi
import re
#import googl
import time
#import sys
#import pprint
import mymixed 
import HTMLParser
import urllib

consumer_key = "i2tfAoL05myUGha0t9HSgA"
consumer_secret = "74cTUol5bPe5n6Ve6rSuuQ5LNbO9PbXdxAsvpfvc4k"

def get_auth_url():
    twitter = OAuthApi(consumer_key, consumer_secret)
    temp_credentials = twitter.getRequestToken()
    return temp_credentials,twitter.getAuthorizationURL(temp_credentials)

def get_access_token(credentials,oauth_verifier):
    twitter = OAuthApi(consumer_key, consumer_secret)
    access_token = twitter.getAccessToken(credentials, oauth_verifier)
    return access_token
    
def unescape(s):
    return HTMLParser.HTMLParser().unescape(s)
    
def GetHomeTimeline(count='20'):
    twitter = OAuthApi(consumer_key, consumer_secret, access_token['oauth_token'], access_token['oauth_token_secret'])
    options={}
    options['count'] = count
    user_timeline = twitter.GetHomeTimeline(options)
    #print user_timeline
    str2 = ''
    for twit in user_timeline:
        str1 = twit['user']['screen_name'] + ":" + unescape(twit['text']).replace('\n',' ')
        str2 = str2 + str1 + '\n'
    return str2
'''
def GetHttpUrl(str1):
   ra = []
   try:
       #iter1 = re.finditer(r'http://\S+',str1,re.S) 
       iter1 = re.finditer(r'http://[\w~#!:.?+=&%@!-\/]+',str1)# 2011 4 11
       for each in iter1 : 
           url = each.group()
           #print 'url is',url
           url1 = 'http://www.google.com/gwt/x?u='
           url2 = googl.Get_Goole_Short_Link(url1 + url)
           time.sleep(0.03)
           if url2:
               url = url2 
               #print url2 
           ra.append(url)
   except:
        pass
   return ra
'''
#obj1 = re.search(r'(?<=@)\w+',str1)

def key_from_string(s):
    """
    Calculate a unique key for an arbitrary  string.
    """
    return   hex(hash(s)) [3:]

def GetHomeTimelinelist(access_token,count='20',all_flag=True,ltth=''):

    #print 'GetHomeTimelinelist',count
    twitter = OAuthApi(consumer_key, consumer_secret, access_token['oauth_token'], access_token['oauth_token_secret'])
    options={}
    options['count'] = count
    user_timeline = twitter.GetHomeTimeline(options)
    #print user_timeline
    str1s = []#twits list
    for twit in user_timeline:
        #print unescape(twit['text']).replace('\n',' ')
        user_name = twit['user']['screen_name']
        user_url = mymixed.get_gwt_twitter_url(user_name)
        str1 = user_name + ":" + unescape(twit['text']).replace('\n',' ') + ' ' + twit['created_at']
        user_img =twit['user']['profile_image_url']#.replace(r'http://a1',r'https://si0')
        obj2 = re.search(r'http://a[0-9][.]',user_img)
        if obj2:
            user_img = user_img.replace(obj2.group(),r'https://si0.')#use https image
        #retweet
        str2 = None
        try:
            str2 = twit['retweeted_status']['user']['screen_name']
            if str2:str1 = str1 + ' ' + str2 + " [reteeted by " + twit['user']['screen_name'] + ']'
        except:
            #print 'exception'
            pass
        
        #source
        str3 = None
        try:
            obj1 = re.search(r'(?<=[>]).+(?=[<])',twit['source'],re.S)
            if obj1:
                str3 = obj1.group() 
            else:
                str3 = twit['source']
            if str3:str1 = str1 + ' via:' + str3
        except:
            pass
        mixed_list = mymixed.get_url_text_at_mixed_list(str1)
        #for a,b in mixed_list:
        #    print a.encode('utf-8')
        #tuple1 = mixed_list,GetHttpUrl(str1)
        t1 = mixed_list,user_img,user_url
        str1s.append(t1)

    
    '''
    last_tt_hash = ''

    con = sqlite3.connect("test.db")
    #con = sqlite3.connect(":memory:")
    c1 = con.cursor()
    c1.execute("select lasttthash from lasttt where user='zdb'")
    l1 = c1.fetchall()
    each = l1[0][0]
    last_tt_hash = str(each)

    c1.execute("update lasttt set lasttthash = '" + key_from_string(str(str1s[0])) + "' where user='zdb'")
    con.commit()
    c1.close()
    '''

    if all_flag:
        return str1s

    #remove duplicate tt
    if ltth == '':#first time
        #print 'first time'
        pass
    else:
        i = 0
        for each__tt in str1s:
            i += 1
            key1 = key_from_string(str(each__tt))
            #print key1,ltth
            if key1 == ltth:
                break; 
        ltth = key_from_string(str(str1s[0]))
        str1s = str1s[0:i-1]

    
    return str1s,ltth

def UpdateStatus(access_token,status):
    twitter = OAuthApi(consumer_key, consumer_secret, access_token['oauth_token'], access_token['oauth_token_secret'])
    try:
        twitter.UpdateStatus(status)
        return "success"
    except Exception,e:
        return str(e)

def MakeApiCall(access_token, call, type="GET", Parameters={}):
    call = call.replace('api/','')
    if Parameters.has_key('status'):
        #Parameters['status'] = urllib.unquote(Parameters['status'])
        Parameters['status'] = Parameters['status'].encode('utf-8')
    twitter = OAuthApi(consumer_key, consumer_secret, access_token['oauth_token'], access_token['oauth_token_secret'])
    return twitter.ApiCall1(call,type,Parameters)
    

#status = base64.decodestring(sys.argv[1]) if len(sys.argv)>1 else ''
'''
status = sys.argv[1] if len(sys.argv)>1 else ''
print status
twitter.UpdateStatus(status)
'''

#pp = pprint.PrettyPrinter(indent=4)
#pp.pprint(user_timeline)
